//
//  SearchDetalisViewController.m
//  A段项目,漫画
//
//  Created by dllo on 15/4/28.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "SearchDetalisViewController.h"
#define HEIGHT  self.view.frame.size.height
#define WIDTH   self.view.frame.size.width
@interface SearchDetalisViewController ()
@property(nonatomic, retain)UIButton *searchButton;
@property(nonatomic, retain)UITextField *searchTextfield;
@property(nonatomic, retain)UIActivityIndicatorView *searchActivity;
@property(nonatomic, retain)NSTimer *searchTimer;
@property(nonatomic, retain)NSMutableArray *searchResult;
@property(nonatomic, retain)UITableView *searchTable;
@property(nonatomic, retain)UIView *witeView;
@end

@implementation SearchDetalisViewController
- (void)resignFirst2{
    [self.searchTextfield resignFirstResponder];
}
//编辑状态
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    //显示搜索框
    [[MidTools shareMidTools].delegate6 makeSearchMarkWithNow:[MidTools shareMidTools].isSearchMarkShow];
}
//关闭状态
- (void)textFieldDidEndEditing:(UITextField *)textField{
    //隐藏搜索框
    [[MidTools shareMidTools].delegate6 makeSearchMarkWithNow:[MidTools shareMidTools].isSearchMarkShow];
}
//空白点击判断
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.searchTextfield resignFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor yellowColor];
    [self createView];
    [self createSearch];
    [MidTools shareMidTools].delegate72 = self;
    [MidTools shareMidTools].delegate82 = self;
    //指明调用者
    [MidTools shareMidTools].searchID = 2;
    //
    [self createWite];
    //之后调用定时器监听数据请求结果
    self.searchTimer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(isFinishAction) userInfo:nil repeats:YES];
}
//取值
- (void)getValue2:(NSString *)mark{
    self.searchTextfield.text = mark;
}
- (void)isFinishAction{
    if ([MidTools shareMidTools].isFinish) {
        if ([MidTools shareMidTools].result.count != 0) {
            //数据解析成功,结束动画
            [self.searchActivity stopAnimating];
            //关闭定时器
            [self.searchTimer setFireDate:[NSDate distantFuture]];
            //获取数据
            self.searchResult = [MidTools shareMidTools].result;
            NSLog(@"接收数据个数:%ld",self.searchResult.count);
            //刷新数据
            NSLog(@"刷新数据");
            [self.searchTable reloadData];
            [self.view bringSubviewToFront:self.searchTable];
        }else{
            [self.searchActivity stopAnimating];
            //关闭定时器
            [self.searchTimer setFireDate:[NSDate distantFuture]];
            UIAlertView *noDataAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有搜索到与关键字相匹配的漫画" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [noDataAlert show];
            [noDataAlert release];
        }
    }
}
- (void)createView{
    self.searchTable = [[UITableView alloc] initWithFrame:CGRectMake(0, -40, WIDTH, HEIGHT) style:UITableViewStyleGrouped];
    self.searchTable.delegate = self;
    self.searchTable.dataSource = self;
    [self.view addSubview:self.searchTable];
    [self.searchTable release];
    CGFloat bili1 = 107 / 80.0;
    self.searchTable.rowHeight = WIDTH / 4.5 * bili1 + 20;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-fanhui-55"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
}
- (void)backAction:(UIButton *)button{
    [[MidTools shareMidTools].result removeAllObjects];
    [MidTools shareMidTools].isFinish = NO;
    [MidTools shareMidTools].searchID = 1;
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createWite{
    self.witeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [self.view addSubview:self.witeView];
    
    self.searchActivity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    self.searchActivity.frame = CGRectMake(0, 0, 200, 200);
    self.searchActivity.center = CGPointMake(WIDTH / 2, HEIGHT / 2);
    [self.witeView addSubview:self.searchActivity];
    [self.searchActivity release];
    self.searchActivity.color = [UIColor blackColor];
    [self.searchActivity startAnimating];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.searchResult.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CartoonDViewController *cdVC = [[CartoonDViewController alloc] init];
    cartoonDestai *cd = self.searchResult[indexPath.row];
    cdVC.comic_id = cd.comic_id;
    [self.navigationController pushViewController:cdVC animated:YES];
    [cdVC release];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *reuse = @"reuse";
    ClassifyDetailTabelViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (cell == nil) {
        cell = [[[ClassifyDetailTabelViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse] autorelease];
    }
    cartoonDestai *cd = self.searchResult[indexPath.row];
    NSURL *url = [NSURL URLWithString:cd.cover_url];
    [cell.myImageView sd_setImageWithURL:url];
    cell.typeLabel.text = cd.type;
    cell.titleLabel.text = cd.title;
    cell.grade_aveLabel.text = cd.grade_ave;
    cell.lastupLabel.text = cd.lastup;
    return cell;
}
- (void)createSearch{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-search.png"] style:UIBarButtonItemStylePlain target:self action:@selector(searchButton:)];
    self.searchTextfield = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, WIDTH / 2, 30)];
    self.navigationItem.titleView = self.searchTextfield;
    self.searchTextfield.layer.borderWidth = 1.5;
    self.searchTextfield.layer.cornerRadius = 10;
    self.searchTextfield.userInteractionEnabled = YES;
    self.searchTextfield.delegate = self;
    self.searchTextfield.layer.borderColor = [UIColor colorWithRed:128 / 255.0 green:128 / 255.0 blue:128 / 255.0 alpha:1].CGColor;
    UIView *paddingView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 5, 40)];
    self.searchTextfield.leftView = paddingView2;
    self.searchTextfield.leftViewMode = UITextFieldViewModeAlways;
    self.searchTextfield.placeholder = @"请输入关键字";
}
- (void)searchButton:(UIButton *)button{
    if (![self.searchTextfield.text isEqual:@""]) {
        NSLog(@"搜索  ");
        //开始动画
        [self.view bringSubviewToFront:self.witeView];
        [self.searchActivity startAnimating];
        //状态改变
        [[MidTools shareMidTools].result removeAllObjects];
        [MidTools shareMidTools].isFinish = NO;
        //用单例进行搜索
        NSString *input = self.searchTextfield.text;
        NSLog(@"%@",input);
        NSString *str = [input stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"%@",str);
        NSString *urlStr = [NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Search/comicSearchListForIos/key_word/%@/listcnt/12/page/1/clientType/0/local_version/2.3.2",str];
        [[MidTools shareMidTools] searchByUrl:urlStr];
        [self.searchTextfield resignFirstResponder];
        
        //存储搜索记录
        //定时器启动
        //先判断是否有相同记录
        BOOL isExit = NO;
        for (NSString *s in [MidTools shareMidTools].searchMark) {
            if ([s isEqual:self.searchTextfield.text]) {
                isExit = YES;
            }
        }
        if (!isExit) {
            NSString *searchMark = self.searchTextfield.text;
            [[MidTools shareMidTools].searchMark addObject:searchMark];
            self.searchTextfield.text = nil;
        }
        
        [self.searchTimer setFireDate:[NSDate distantPast]];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"搜索关键字不能为空" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        [alert release];
    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
